<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="75%"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="170px"
    >
      <el-form-item label="分享类型" prop="shareType">
        <el-select
          style="width:150px;"
          @change="dateChanged"
          v-model="dataForm.shareType"
          placeholder="请选择"
        >
          <el-option v-for="(item,i) in dateSelect" :key="i" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="助力成功文案" v-if="dataForm.shareType === 8 || dataForm.shareType === 9">
        <el-input v-model="dataForm.congratulationInfo" placeholder="请输入助力成功文案"></el-input>
        <div style="color: #999;">例：恭喜您助力成功，获得[love]爱心值，快去分享给好友吧</div>
      </el-form-item>
      <el-form-item label="任务完成文案" v-if="dataForm.shareType === 10"
                    prop="congratulationInfo"
                    :rules="[
            { required: true, message: '任务完成文案不能为空', trigger: 'blur' },
          ]"
      >
        <el-input v-model="dataForm.congratulationInfo" placeholder="请输入任务完成文案"></el-input>
        <div style="color: #999;">例：恭喜你完成了今天的学习任务，\n快去分享你的学习成就吧！</div>
      </el-form-item>
      <el-form-item label="邀请助力文案" v-if="dataForm.shareType === 8 || dataForm.shareType === 9">
        <el-input v-model="dataForm.invitationInfo" type="textarea" :rows="3" placeholder="请输入邀请助力文案"></el-input>
        <div style="color: #999;" v-if="dataForm.shareType === 8">{{invitationInfoPerson}}</div>
        <div style="color: #999;" v-if="dataForm.shareType === 9">{{invitationInfoTeam}}</div>
      </el-form-item>
      <el-form-item label="邀请卡标题文案" v-if="dataForm.shareType === 10"
                    prop="sharePageDesc"
                    :rules="[
            { required: true, message: '邀请卡标题文案不能为空', trigger: 'blur' },
          ]">
        <el-input v-model="dataForm.sharePageDesc" placeholder="请输入邀请卡标题文案"></el-input>
        <div style="color: #999;">例：邀您组队读好书</div>
      </el-form-item>
      <el-form-item label="邀请卡标题文案" v-if="dataForm.shareType === 8 || dataForm.shareType === 9">
        <el-input v-model="dataForm.sharePageDesc"></el-input>
      </el-form-item>
      <el-form-item label="邀请卡文案" prop="sharePageInfo">
        <el-input v-model="dataForm.sharePageInfo" placeholder="邀请卡文案"></el-input>
        <div style="color: #999;" v-if="dataForm.shareType === 10">例：长按识别二维码，开始畅听\n查看笔记全文</div>
      </el-form-item>
      <el-form-item label="邀请卡背景图" prop="sharePageImageUrls" v-if="dataForm.shareType!=7">
        <el-upload
          :action="url"
          list-type="picture-card"
          :before-upload="handlePictureCardPreview"
          :on-success="PictureCardPreview"
          :file-list="fileLists"
          :on-remove="handleRemove"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="50%" :src="dialogImageUrls" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item v-if="dataForm.shareType==7" label="邀请卡背景图" prop="sharePageImageUrls" class="noteshare">
        <!--邀请卡一坨-->
        <div class="invitecardbg" v-for="(item, index) in invitecard">
          <div class="flexinvite">
            <div class="img"><img :src="item.bgImgUrl" alt=""></div>
            <div class="flexcontent">
              <div class="flex">
                <div class="title">缩略图背景色</div>
                <div class="inputtext"><el-input v-model="item.thumbColor" @blur="checkcolor" placeholder="请输入色值"></el-input></div>
              </div>
              <div class="flex">
                <div class="title">缩略图</div>
                <div class="inputtext">
                  <el-upload
                    class="upload-demo"
                    :action="url"
                    :before-upload="handleBefore"
                    :on-success="(response, file,fileList)=>{ return handlePreview(response, file,fileList,index)}"
                    :on-remove="(file,fileList)=>{ return handleRemovesuo(file,fileList,index)}"
                    :file-list="item.fileList"
                    list-type="picture">
                    <el-button size="small" type="primary">点击上传</el-button>
                  </el-upload>
                </div>
              </div>
              <div class="flex">
                <div class="title">样式名称</div>
                <div class="inputtext"><el-input v-model="item.styleName" @blur="checkstylename" placeholder=""></el-input></div>
              </div>
              <div class="flex">
                <div class="title">名称颜色</div>
                <div class="inputtext"><el-input v-model="item.thumbnailTextColor" @blur="checkcolor"  placeholder="请输入色值"></el-input></div>
              </div>
            </div>
            <div class="flexcontent">
              <div class="flex">
                <div class="title">日期文案颜色</div>
                <div class="inputtext"><el-input v-model="item.dateTextColor" @blur="checkcolor" placeholder="请输入色值"></el-input></div>
              </div>
              <div class="flex">
                <div class="title">邀请卡文案颜色</div>
                <div class="inputtext"><el-input v-model="item.sloganTextColor" @blur="checkcolor" placeholder="请输入色值"></el-input></div>
              </div>
              <div class="flex">
                <div class="title">二维码文案颜色</div>
                <div class="inputtext"><el-input v-model="item.qrcodeDescTextColor" @blur="checkcolor" placeholder="请输入色值"></el-input></div>
              </div>
            </div>
          </div>
          <div><el-button type='danger' @click="deleteinvite(index)">删除</el-button></div>
        </div>
        <el-upload
          :action="url"
          list-type="picture-card"
          :before-upload="handlePictureCardPreview"
          :on-success="PictureCardPreview"
          :file-list="fileLists"
          :on-remove="handleRemove"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="50%" :src="dialogImageUrls" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="邀请卡分享二维码链接" prop="sharePageShareUrl">
        <el-input v-model="dataForm.sharePageShareUrl" placeholder="邀请卡分享二维码链接"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.shareType!=10" label="分享图标" prop="shareImg" :class="{ noChange : disableds }">
        <img :src="dataForm.shareImg" v-if="dataForm.id" style="width: 140px;height: 140px;">
        <img :src="dataForm.shareImg" v-if="!dataForm.id" style="width: 140px;height: 140px;">
        <el-upload
          class="upload-demo"
          :action="url"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          :disabled="disableds"
          list-type="picture"
        >
          <el-button size="small" type="primary" :disabled="disableds">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">{{ dataForm.shareType === 7?'默认展示书籍缩略图':'只能上传png/jpg/jpeg文件且大小不超过250KB' }}</div>
        </el-upload>
      </el-form-item>
      <el-form-item v-if="dataForm.shareType!=10" label="分享标题" prop="shareTitle" :class="{ noChange : disableds }">
        <el-input v-model="dataForm.shareTitle" :placeholder="placeholders" :disabled="disableds"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.shareType!=10" label="分享文案" prop="shareDesc" :class="{ noChange : disableds }">
        <el-input v-model="dataForm.shareDesc" placeholder="分享文案" :disabled="disableds"></el-input>
      </el-form-item>
      <el-form-item v-if="dataForm.shareType!=10" label="分享链接" prop="shareUrl">
        <el-input v-model="dataForm.shareUrl" placeholder="分享链接"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">返回</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="iskans">确定</el-button>
      <!--<el-button @click="visible = false" v-if="iskans">返回</el-button>-->
    </span>
  </el-dialog>
</template>
<script>
  export default {
    data() {
      return {
        fileList2: [],
        invitecard: [],
        invitationInfoPerson: '例：已为[partnerName]的<br>心愿助力[credit]学分，邀请您一起为[partnerName]<br>的心愿助力',
        invitationInfoTeam: '例：[captainName]的团队<br>为[partnerName]的心愿助力[day]天，<br>邀请您一起为[partnerName]<br>的心愿助力!',
        visible: false,
        fileLists: [],
        placeholders: '[nickname]为分享者昵称，例：[nickname]邀请您一起学习',
        disableds: false,
        dataForm: {
          id: 0,
          shareDesc: '',
          shareImg: '',
          shareType: 1,
          sharePageImageUrls: [],
          sharePageInfo: '',
          sharePageShareUrl: '',
          shareTitle: '',
          shareUrl: ''
        },
        dataRule: {
          sharePageInfo: [
            {required: true, message: '邀请文案不能为空', trigger: 'blur'}
          ],
          shareType: [
            {required: true, message: '选择类型', trigger: 'blur'}
          ],
          sharePageShareUrl: [
            {
              pattern: /(http|https|yiban):\/\/([\w.]+\/?)\S*/,
              required: true,
              message: '邀请卡分享二维码链接不能为空',
              trigger: 'blur'
            }
          ],
          shareTitle: [
            {required: true, message: '分享标题不能为空', trigger: 'blur'}
          ],
          sharePageImageUrls: [
            {required: true, message: '邀请卡背景图不能为空', trigger: 'blur'}
          ],
          shareDesc: [
            {required: true, message: '分享文案不能为空', trigger: 'blur'}
          ],
          shareUrl: [
            {pattern: /(http|https|yiban):\/\/([\w.]+\/?)\S*/, required: true, message: '分享链接不能为空', trigger: 'blur'}
          ]
        },
        dateSelect: [
          {
            label: '邀请好友',
            value: 1
          }, {
            label: '书籍分享',
            value: 2
          }, {
            label: '公益活动分享',
            value: 3
          }, {
            label: '知识彩蛋分享',
            value: 4
          }, {
            label: '伴学记录分享',
            value: 5
          }, {
            label: '学习记录分享',
            value: 6
          }, {
            label: '笔记分享',
            value: 7
          }, {
            label: '个人助力海报',
            value: 8
          }, {
            label: '团队助力海报',
            value: 9
          }, {
            label: '学习成就卡分享',
            value: 10
          }
        ],
        url: '',
        dialogVisible: false,
        dialogImageUrls: '',
        iskans: false,
        title: ''
      }
    },
    mounted() {
      this.url = this.$http.adornUrl(
        `/operate/shareInfo/upload?token=${this.$cookie.get('token')}`
      )
    },
    methods: {
      init(id) {
        this.dataForm.id = id || 0
        this.fileLists = []
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(
                `/operate/shareInfo/info/${this.dataForm.id}`
              ),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                var json = []
                data.shareInfo.sharePageImageUrls.forEach(item => {
                  var obj = {
                    url: item
                  }
                  json.push(obj)
                })
                this.fileLists = json
                this.dataForm = data.shareInfo
                if (data.shareInfo.shareType === 2) {
                  this.placeholders = '[nickname]邀你共读《[bookname]》'
                  this.disableds = true
                  this.dataForm.shareTitle = '[nickname]邀您共读《[bookname]》'
                  this.dataForm.shareDesc = '【时间点亮梦想，用心陪伴成长】'
                  this.dataForm.shareImg = 'https://yiban-app-resource.oss-cn-beijing.aliyuncs.com/wx-info-dev/shareInfo_image/20190813626d9d7611534ea69b38fce539480374.jpg'
                } else if (data.shareInfo.shareType === 7) {
                  if(data.shareInfo.shareCardStyles) {
                    this.invitecard = data.shareInfo.shareCardStyles
                    this.invitecard.map((item, index) => {
                      if(item.thumbImg) {
                        item.fileList = [{url:item.thumbImg,name:'缩略图'}]
                      }
                    })
                  }
                  this.placeholders = ''
                  this.disableds = true
                  this.dataForm.shareTitle = '《[bookname]》读书笔记'
                  this.dataForm.shareDesc = '默认显示笔记内容'
                  this.dataForm.shareImg = 'https://yiban-app-resource.oss-cn-beijing.aliyuncs.com/wx-info-dev/shareInfo_image/20190813626d9d7611534ea69b38fce539480374.jpg'
                } else {
                  this.placeholders = '[nickname]为分享者昵称，例：[nickname]邀请您一起学习'
                  this.disableds = false
                }
              }
            });
          }
        });
      },
      resetValid() {
        delete this.dataRule.sharePageInfo
      },
      checkcolor(e) {
        if(e.srcElement.value.indexOf('#')>-1&&(e.srcElement.value.split('#')[1].length === 3||e.srcElement.value.split('#')[1].length === 6)){
          e.srcElement.style.border = '1px solid #67c23a'
        } else {
          e.srcElement.style.border = '1px solid red'
        }
      },
      checkstylename(e) {
        if(e.srcElement.value){
          e.srcElement.style.border = '1px solid #67c23a'
        } else {
          e.srcElement.style.border = '1px solid red'
        }
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handleRemovesuo(file,fileList,index) {
        this.invitecard[index].thumbImg = ''
      },
      handlePreview(response, file, fileList, index) {
        if (response && response.code === 0) {
          this.invitecard[index].thumbImg = response.url
          let cardobj = this.invitecard[index]
          cardobj.fileList = [fileList[fileList.length-1]]
          this.invitecard.splice(index,1,cardobj)
        } else {
          this.$message.error(response.msg)
        }
      },
      deleteinvite(index) {
        this.invitecard.splice(index, 1)
      },
      handleAvatarSuccess(response, file, fileList) {
        this.fileList = fileList
        this.successNum++
        if (response && response.code === 0) {
          if (this.num === this.successNum) {
            // this.$confirm('操作成功, 是否继续操作?', '提示', {
            //   confirmButtonText: '确定',
            //   cancelButtonText: '取消',
            //   type: 'warning'
            // }).catch(() => {
            //   this.visible = false
            // })
          }
          this.dataForm.shareImg = response.url
        } else {
          this.$message.error(response.msg)
        }
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif'
        if (!isJPG) {
          this.$message.error('上传封面只能是图片!')
        }
        const isSize = new Promise(function (resolve, reject) {
          // let width = 1029;
          // let height = 390;
          let size = 250 * 1024
          let _URL = window.URL || window.webkitURL
          let img = new Image()
          img.onload = function () {
            // let valid = img.width === width && img.height === height
            // valid ? resolve() : reject()
            // resolve()
            let valid = size >= file.size
            valid ? resolve() : reject()
          }
          img.src = _URL.createObjectURL(file)
        }).then(
          () => {
            return file
          },
          () => {
            this.$message.error('上传的banner缩略图必须是小于250kb!')
            return Promise.reject()
          }
        );
        return isJPG && isSize
      },
      // 表单提交
      dataFormSubmit() {
        if(this.dataForm.shareType === 10) {
          delete this.dataRule.shareTitle
          delete this.dataRule.shareDesc
          delete this.dataRule.shareUrl
        }
        this.dataForm.shareCardStyles = this.invitecard
        if(this.dataForm.shareType === 7) {
          let iserror = false,
            errtext = ''
          this.invitecard.map((item)=> {
            if(!item.dateTextColor||!item.sloganTextColor||!item.qrcodeDescTextColor||!item.thumbnailTextColor||!item.thumbColor) {
              errtext = '请检查是否填写了所有的颜色值～'
              iserror = true
            }
            if(!item.styleName) {
              errtext ='请检查是否填写了所有的样式名～'
              iserror = true
            }
          })
          if(iserror) {
            this.$message.warning(errtext)
            return false
          }
          this.dataForm.sharePageImageUrls = ['https://yiban-c.ivykid.com/yb-info-prd/shareInfo_image/20191218723311b65cc34d539925c0ab8f2320ba.png', 'https://yiban-c.ivykid.com/yb-info-prd/shareInfo_image/201912181971fda373554b09bddcf716f23906a4.png', 'https://yiban-c.ivykid.com/yb-info-prd/shareInfo_image/2019122088cb6614c35a4a5690a70af34b33928f.png']
        }
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            if(this.dataForm.shareType !== 7 && this.dataForm.shareType !== 10) {
              if(this.dataForm.shareTitle.indexOf('[nickname]') === -1) {
                this.$message.error('分享标题需要输入[nickname]');
                return false
              }
            }
            this.dataForm.id = this.dataForm.id === 0 ? undefined : this.dataForm.id
            this.$http({
              url: this.$http.adornUrl(
                `/operate/shareInfo/${!this.dataForm.id ? "save" : "update"}`
              ),
              method: 'post',
              data: this.$http.adornData(this.dataForm)
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          }
        });
      },
      handleRemove: function (file, fileList) {
        var _this = this
        _this.dataForm.sharePageImageUrls = []
        var obj = []
        fileList.forEach(item => {
          if (item.response) {
            obj.push(item.response.url)
          } else {
            obj.push(item.url)
          }
        })
        _this.dataForm.sharePageImageUrls = obj
      },
      handleBefore(file) {
        const isJPG = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif'
        if (!isJPG) {
          this.$message.error('上传封面只能是图片!')
        }
        const is250K = file.size / 1024 < 250
        if (!is250K) {
          this.$message.error('上传的图片要小于250KB!')
        }
        return isJPG && is250K
      },
      handlePictureCardPreview: function (file) {
        const isJPG = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif'
        if (!isJPG) {
          this.$message.error('上传封面只能是图片!')
        }
        const isSize = new Promise(function (resolve, reject) {
          // let width = 1029;
          // let height = 390;
          let size = 250 * 1024
          let _URL = window.URL || window.webkitURL
          let img = new Image()
          img.onload = function () {
            let valid = size >= file.size
            valid ? resolve() : reject()
            // resolve()
          }
          img.src = _URL.createObjectURL(file)
        }).then(
          () => {
            return file
          },
          () => {
            this.$message.error('上传图片需小于250KB!')
            return Promise.reject()
          }
        );
        return isJPG && isSize
      },
      dateChanged: function (val) {
        if (val === 2) {
          this.placeholders = '[nickname]邀你共读《[bookname]》'
          this.disableds = true
          this.dataForm.shareTitle = '[nickname]邀您共读《[bookname]》'
          this.dataForm.shareDesc = '【时间点亮梦想，用心陪伴成长】'
          this.dataForm.shareImg = 'https://yiban-app-resource.oss-cn-beijing.aliyuncs.com/wx-info-dev/shareInfo_image/20190813626d9d7611534ea69b38fce539480374.jpg'
        } else if (val === 7) {
          this.placeholders = ''
          this.disableds = true
          this.dataForm.shareTitle = '《[bookname]》读书笔记'
          this.dataForm.shareDesc = '默认显示笔记内容'
          this.dataForm.shareImg = 'https://yiban-app-resource.oss-cn-beijing.aliyuncs.com/wx-info-dev/shareInfo_image/20190813626d9d7611534ea69b38fce539480374.jpg'
        } else {
          this.placeholders = '[nickname]为分享者昵称，例：[nickname]邀请您一起学习'
          this.disableds = false
          this.dataForm.shareTitle = ''
          this.dataForm.shareDesc = ''
          this.dataForm.shareImg = ''
        }
      },
      PictureCardPreview: function (response, file, fileList) {
        if (response && response.code === 0) {
          // if (this.num === this.successNum) {
          //   // this.$confirm('操作成功, 是否继续操作?', '提示', {
          //   //   confirmButtonText: '确定',
          //   //   cancelButtonText: '取消',
          //   //   type: 'warning'
          //   // }).catch(() => {
          //   //   this.visible = false
          //   // })
          // }
          // this.dataForm.shareImg = response.url
          var _this = this
          _this.dataForm.sharePageImageUrls = []
          var obj = []
          fileList.forEach(item => {
            if (item.response) {
              obj.push(item.response.url)
            } else {
              obj.push(item.url)
            }
          })
          this.invitecard.push({bgImgUrl: response.url, fileList:[]})
          _this.dataForm.sharePageImageUrls = obj
          this.dialogImageUrls = file.url
        } else {
          return this.$message.error(response.msg)
        }
      }
    }
  }
</script>
<style>
  .noChange .el-form-item__label{
    color: #bbb!important;
  }
  .noteshare .el-upload-list--picture-card{
    display: none;
  }
  .noteshare .el-upload-list__item-name {
    width: 80px;
    overflow : hidden;
    text-overflow: ellipsis;
  }
</style>
<style lang="scss" scoped>
  img{
    width: 100%;
    max-height: 100%;
    border-radius: 4px;
  }
  .invitecardbg{
    padding-bottom: 20px;
    margin-bottom: 20px;
    border-bottom: 1px solid #efefef;
  }
  .flexinvite{
    display: flex;
    .img{
      width: 150px;
      height: 150px;
    }
    .flex{
      margin: 10px 0;
      display: flex;
      .title{
        width: 100px;
        text-align: right;
        margin-right: 20px;
        margin-left: 30px;
      }
    }
  }
</style>
